const User = require('../models/User');
const TradeService = require('./TradeService');
const DatabaseService = require('./DatabaseService');
const StockService = require('./StockService');

class UserService {
  constructor() {
    this.users = new Map(); // 仍然保留内存中的用户映射以提高性能
    this.initializeSampleData();
  }

  // 初始化示例数据
  initializeSampleData() {
    // 注意：实际应用中这些用户应该存储在数据库中
    const sampleUsers = [
      new User(1, 'trader1', 'trader1@example.com', 100000),
      new User(2, 'trader2', 'trader2@example.com', 50000)
    ];

    sampleUsers.forEach(user => {
      this.users.set(user.id, user);
    });
  }

  // 创建用户
  createUser(username, email, initialBalance) {
    // 在实际应用中，这里应该将用户保存到数据库
    // 这里我们仍然使用内存存储以简化示例
    const userId = this.users.size + 1;
    const user = new User(userId, username, email, initialBalance);
    
    this.users.set(userId, user);
    return user.getAccountInfo();
  }

  // 获取用户信息
  getUser(userId) {
    const user = this.users.get(userId);
    return user ? user.getAccountInfo() : null;
  }

  // 获取所有用户
  getAllUsers() {
    return Array.from(this.users.values()).map(user => user.getAccountInfo());
  }

  // 用户买入股票
  buyStock(userId, symbol, quantity, price) {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }

    // 创建交易
    const trade = TradeService.createTrade(symbol, 'BUY', quantity, price);
    
    // 执行交易
    TradeService.executeTrade(trade.id);
    
    // 更新用户账户
    user.buyStock(symbol, quantity, price);
    
    // 添加到用户交易历史
    user.addTradeToHistory(trade);
    
    return {
      success: true,
      message: 'Stock purchase successful',
      trade: trade,
      accountInfo: user.getAccountInfo()
    };
  }

  // 用户卖出股票
  sellStock(userId, symbol, quantity, price) {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }

    // 创建交易
    const trade = TradeService.createTrade(symbol, 'SELL', quantity, price);
    
    // 执行交易
    TradeService.executeTrade(trade.id);
    
    // 更新用户账户
    user.sellStock(symbol, quantity, price);
    
    // 添加到用户交易历史
    user.addTradeToHistory(trade);
    
    return {
      success: true,
      message: 'Stock sale successful',
      trade: trade,
      accountInfo: user.getAccountInfo()
    };
  }

  // 获取用户投资组合
  getUserPortfolio(userId) {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    return user.getPortfolio();
  }

  // 获取用户交易历史
  getUserTradeHistory(userId) {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    return user.getTradeHistory();
  }
  
  // 数据库集成方法
  // 创建数据库用户
  static async createDatabaseUser(username, email, passwordHash, initialBalance = 0) {
    try {
      const user = DatabaseService.createUser(username, email, passwordHash, initialBalance);
      return user;
    } catch (error) {
      throw new Error(`Failed to create user in database: ${error.message}`);
    }
  }
  
  // 根据用户名获取数据库用户
  static async getDatabaseUserByUsername(username) {
    try {
      const user = DatabaseService.getUserByUsername(username);
      return user;
    } catch (error) {
      throw new Error(`Failed to get user from database: ${error.message}`);
    }
  }
  
  // 根据ID获取数据库用户
  static async getDatabaseUserById(id) {
    try {
      const user = DatabaseService.getUserById(id);
      return user;
    } catch (error) {
      throw new Error(`Failed to get user from database: ${error.message}`);
    }
  }
}

module.exports = new UserService(); // 单例模式